<?php
namespace control;
/*
*币别类
*/

class currencyClass extends adIndexClass
{
    private const page = 'currency';
    private const table = 'currency';
    private const title = '币别';

    /**
     * 计算精度
     * @param $number
     * @return int
     */

    public static function calculateDecimal($number): int
    {
        if (empty($number)){
            return 0;
        }
        if (!is_numeric($number)){
            return 1;
        }
        if (str_contains($number,'e') || str_contains($number,'E')){
            $number =strtoupper($number);
            $temp = explode('E',$number);
            return pow(10,abs($temp[1]));
        }else{
            return pow(10,strlen(substr(strrchr($number, "."), 1)));
        }
    }

    /**
     * 整数转小数
     */
    public static function intToDecimal($money,$baseUnit=1): float|int
    {
        return $baseUnit>0?floatval($money/$baseUnit):0;
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'code'          => [
                        'name'  => "编码",
                        'width' => 400,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => '名称',
                        'width' => 400,
                    ],
                    'rate'         => [
                        'name'  => '汇率',
                        'width' => 400,
                    ],
                    'isBase'          => [
                        'name'  => '是否本位币',
                        'width' => 350,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "编码" => text(array("name" => "code")),
                    "名称"   => text(array("name" => "name")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{id:'".suiji()."'})\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "name" => $this->post('name'),
            "code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            'coid' => self::$coid
        );
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal));
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'updateTime',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                'edit' => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'".$array['id']."'})"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'rate':
                        $row[] = $array['rate']/$array['accuracy'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    /**
     * 启用/停用
     */
    public function edit(): bool|string
    {
        $info = query(self::table,"id = '".$this->post('id')."'");
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must."编码：" =>text(array('name'=>'code','value'=>$info['code'])),
            ),
            array(
                must."名称：" => text(array('name'=>'name','value'=>$info['name'])),
            ),
            array(
                must."汇率：" => text(array('name'=>'rate','class'=>'text','value'=>$info['id']?$info['rate']/$info['accuracy']:'','type'=>'number')).componentClass::tipComponent('1此币种=多少本位币'),
            ),
        )));
        //返回
        return $this->layer(array("title" => "编辑", "height" => 300, "width" => 600, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $accuracy = self::calculateDecimal($this->post('rate'));
        $field = [
            'code' => $this->post('code'),
            'name' => $this->post('name'),
            'rate' => $this->post('rate')*$accuracy,
            'accuracy'=>$accuracy
        ];
        $annotation = [
            'code' => '编码',
            'name' => '名称',
            'rate' => '汇率',
        ];
        $rules = [
            'code' => 'required',
            'name' => 'required',
            'rate' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::total(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and code = '$field[code]' and id !='$id'"))) {
            $json['warn'] = '已存在此编码的币别';
        } elseif (static::total(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and name = '$field[name]' and id !='$id'"))) {
            $json['warn'] = '已存在此名称的币别';
        } else {
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'coid' => self::$coid,
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }
        resp:
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['isBase'] == '是') {
                    $warn = "删除失败：本位币不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "【" . $info['name'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}

